#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use PairedReadFlagStat;
use DepthCoverage;
use VariantEval;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($sample_name, $insert, $speekfile);
my @argv = @ARGV;
&GetOptions("insert!"=> \$insert,
						"speekfile=s" => \$speekfile,
            "sample_name=s" => \$sample_name);

if ((!$sample_name)) {
	die "usage: $0 --sample_name PSP7000 --speekfile --insert\n(use --insert only when data are ready to be inserted into mysql table)\n";
}

$speekfile = "${sample_name}_speek.txt" if ((!$speekfile));
if ($insert) {
	print STDERR "$sample_name to be inserted into Metric from $speekfile.\n";
}
else {
	# no "insert"; just dumps arguments
	print Dumper(@argv);
}

my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3}) or die "Couldn't connect to database: " . DBI->errstr;
$dbh->{AutoCommit} = 0;
exit unless ($insert == 1);
my $sth = $dbh->prepare("INSERT INTO Metric VALUES (?,?,?,?)") or die "Couldn't prepare statement: " . $dbh->errstr;
open(FIN, $speekfile) or die "Couldn't open $speekfile\n";
my @all_metrics = <FIN>;
#printf "%d\n", scalar @all_metrics;
close FIN;

my $success = 1;
foreach my $line (@all_metrics) {
	chomp($line);
	my @arr = split(/\t/, $line);
#	printf STDERR "$line\n";
#	next if ($arr[2] =~ /13|16|19|22|25|28|31/);
	$success &&= $sth->execute($arr[0],$arr[1],$arr[2],$arr[3]) or die "Couldn't execute statement: " . $sth->errstr;
}
my $result = ($success ? $dbh->commit : $dbh->rollback);
die "Couldn't finish transaction: " . $dbh->errstr unless ($result);
printf STDERR "%d metrics of $sample_name inserted into Metric with success (yes/no:1/0) $success.\n", scalar @all_metrics;
$dbh->disconnect;